import 'dart:async';
import 'package:flutter/material.dart';

/// 全局倒计时管理器
/// 解决 ListView 中每个 cell 独立倒计时导致的性能问题和状态错乱
class CountdownManager {
  static final CountdownManager _instance = CountdownManager._internal();
  factory CountdownManager() => _instance;
  CountdownManager._internal();

  Timer? _globalTimer;
  final Map<String, CountdownData> _countdownData = {};
  final List<VoidCallback> _listeners = [];

  /// 启动全局倒计时
  void startGlobalCountdown() {
    if (_globalTimer != null) return;
    
    _globalTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      _updateAllCountdowns();
    });
  }

  /// 停止全局倒计时
  void stopGlobalCountdown() {
    _globalTimer?.cancel();
    _globalTimer = null;
  }

  /// 添加倒计时数据
  void addCountdown(String productId, String currentTime, String endTime) {
    try {
      DateTime current = DateTime.parse(currentTime);
      DateTime end = DateTime.parse(endTime);
      Duration remaining = end.difference(current);
      
      if (remaining.isNegative) {
        _countdownData[productId] = CountdownData(
          productId: productId,
          hours: 0,
          minutes: 0,
          seconds: 0,
          isActive: false,
        );
      } else {
        _countdownData[productId] = CountdownData(
          productId: productId,
          hours: remaining.inHours,
          minutes: remaining.inMinutes % 60,
          seconds: remaining.inSeconds % 60,
          isActive: true,
        );
      }
    } catch (e) {
      debugPrint('倒计时数据解析错误: $e');
      _countdownData[productId] = CountdownData(
        productId: productId,
        hours: 0,
        minutes: 0,
        seconds: 0,
        isActive: false,
      );
    }
  }

  /// 获取倒计时数据
  CountdownData? getCountdown(String productId) {
    return _countdownData[productId];
  }

  /// 移除倒计时数据
  void removeCountdown(String productId) {
    _countdownData.remove(productId);
  }

  /// 清除所有倒计时数据
  void clearAllCountdowns() {
    _countdownData.clear();
  }

  /// 添加监听器
  void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }

  /// 移除监听器
  void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }

  /// 更新所有倒计时
  void _updateAllCountdowns() {
    bool hasChanges = false;
    
    _countdownData.forEach((productId, data) {
      if (data.isActive) {
        if (data.seconds > 0) {
          data.seconds--;
        } else if (data.minutes > 0) {
          data.minutes--;
          data.seconds = 59;
        } else if (data.hours > 0) {
          data.hours--;
          data.minutes = 59;
          data.seconds = 59;
        } else {
          // 倒计时结束
          data.isActive = false;
        }
        hasChanges = true;
      }
    });

    if (hasChanges) {
      _notifyListeners();
    }
  }

  /// 通知所有监听器
  void _notifyListeners() {
    for (var listener in _listeners) {
      try {
        listener();
      } catch (e) {
        debugPrint('倒计时监听器错误: $e');
      }
    }
  }

  /// 销毁管理器
  void dispose() {
    stopGlobalCountdown();
    clearAllCountdowns();
    _listeners.clear();
  }
}

/// 倒计时数据类
class CountdownData {
  final String productId;
  int hours;
  int minutes;
  int seconds;
  bool isActive;

  CountdownData({
    required this.productId,
    required this.hours,
    required this.minutes,
    required this.seconds,
    required this.isActive,
  });

  /// 获取格式化的时间字符串
  String get formattedTime {
    return '${hours.toString().padLeft(2, '0')}H:${minutes.toString().padLeft(2, '0')}M:${seconds.toString().padLeft(2, '0')}S';
  }

  /// 检查是否还有剩余时间
  bool get hasTimeLeft {
    return hours > 0 || minutes > 0 || seconds > 0;
  }
}
